package com.xqls.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import com.xqls.dal.model.TScheduleJob;
/** 
 * 通过反射调用scheduleJob中定义的方法 
 *  
 * @param scheduleJob 
 */ 
public class TaskUtils implements BeanFactoryAware{
	public final static Logger log = Logger.getLogger(TaskUtils.class);  
	  
    private static BeanFactory beanFactory; 
    
    @SuppressWarnings("unchecked")
	public static void invokMethod(TScheduleJob scheduleJob) {  
        Object object = null;  
        Class clazz = null;  
                //springId不为空先按springId查找bean  
        if (StringUtils.isNotBlank(scheduleJob.getfSpringId())) {  
            System.out.println("springid::::::::"+scheduleJob.getfSpringId());  
            System.out.println("beanFactory======="+beanFactory);  
            object = beanFactory.getBean(scheduleJob.getfSpringId());  
        } else if (StringUtils.isNotBlank(scheduleJob.getfBeanClass())) {  
            try {  
                clazz = Class.forName(scheduleJob.getfBeanClass());  
                object = clazz.newInstance();  
            } catch (Exception e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
  
        }
        if (object == null) {  
            log.error("任务名称 = [" + scheduleJob.getfJobName() + "]---------------未启动成功，请检查是否配置正确！！！");  
            return;  
        }  
        clazz = object.getClass();  
        Method method = null;  
        try {  
            method = clazz.getDeclaredMethod(scheduleJob.getfMethodName());  
        } catch (NoSuchMethodException e) {  
            log.error("任务名称 = [" + scheduleJob.getfJobName() + "]---------------未启动成功，方法名设置错误！！！");  
        } catch (SecurityException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        if (method != null) {  
            try {  
                method.invoke(object);  
            } catch (IllegalAccessException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (IllegalArgumentException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (InvocationTargetException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
          
    }    
    
	@Override
	public void setBeanFactory(BeanFactory bean) throws BeansException {
		beanFactory=bean;
	}

}
